﻿/* Copyright DefaultDependencyResolver.cs Killian Bourrié
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */

namespace NTracker.Injection
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Configs;
    using Toolkit;

    public sealed class DefaultDependencyResolver : IDependencyResolver
    {
        public DefaultDependencyResolver()
        {
            this.Catalog = DependencyCatalog.Instance;
        }

        public DefaultDependencyResolver(Func<Type, object> returnCustomValues)
        {
            this.Catalog = DependencyCatalog.Instance;
            this.ReturnCustomValues = returnCustomValues;
        }

        public DefaultDependencyResolver(Func<Type, object> returnCustomValues, IBaseCatalog catalog)
        {
            this.Catalog = catalog;
            this.ReturnCustomValues = returnCustomValues;
        }

        public IBaseCatalog Catalog { get; set; }

        public Func<Type, object> ReturnCustomValues { get; set; }

        public ReflectionCaller Resolve(string contractName, params object[] args)
        {
            Type type = this.ExtractTypeFromCatalog(contractName);
            object container = new object();
            if (type != null)
            {
                container = Activator.CreateInstance(type, args);
            }

            return new ReflectionCaller(container, this);
        }

        public T Resolve<T>(string contractName, params object[] args)
        {
            Type expectedType = typeof(T);
            Type type = this.ExtractTypeFromCatalog(contractName);
            object container = new object();
            if (type != null && type == expectedType)
            {
                container = Activator.CreateInstance(type, args);
            }

            return (T)container;
        }

        public void UpdateDependencies()
        {
            this.Catalog.RefreshDependencies(); 
        }

        private Type ExtractTypeFromCatalog(string contractName)
        {
            // Retrieve the type in dependency catalog
            IEnumerable<Type> types = this.Catalog.Dependencies
                .Where(d => d.Key == contractName)
                .Select(d => d.Value);

            return types.Count() != C.EMPTY ? types.FirstOrDefault() : typeof(object);
        }
    }
}
